import { BaseReactElementState, BaseReactElement, reactControl, BaseReactElementControl } from "pao-aop-client";

import React from "react";

import SignFrameLayout, { InputType } from "src/business/style-components/sign-frame-layout";
import { addon, getObject, Ref, log, PermissionState } from "pao-aop";
import { NTOperationTable } from "src/business/components/operation-table";
import { ICompanyTemplateSignService, Condition, CompanySign } from "src/models/companySign";
import { IIndustryService } from "src/models/industry";
import { change_structure, onRowSkipClick, ROUTE_PATH } from "../../app/util-tool";
import { IndustryInternetSignAppStorage } from "../../app/appStorage";
import { notification } from "antd";
import { PermissionList } from "../../app/permission";
/**
 * 组件：企业模板标识视图控件状态
 * 
 */
export interface CompanyTemplateViewState extends BaseReactElementState {
    data_source?: CompanySign[];
    /** 当前第几页 */
    page?: number;
    /** 当前每页数 */
    pageSize?: number;
    /** 数据总条数 */
    total_data?: number;
    /** 查询条件对象 */
    condition?: Condition;
    /** 行业类型列表 */
    industry_data?: any;
    /** 滚动条 */
    loading?: boolean;
}
const edit_form_items_props = [
    {
        type: InputType.input,
        label: "企业模板名称",
        decorator_id: "handle_name",
        option: {
            placeholder: "请输入企业模板名称"
        }
    },
    {
        type: InputType.input,
        label: "企业模板标识",
        decorator_id: "handle_code",
        option: {
            placeholder: "请输入企业模板标识"
        }
    },
    {
        type: InputType.date,
        label: "创建时间",
        decorator_id: "create_date",
    },
];
/**
 * 组件：企业模板标识视图控件
 * 描述
 */
export class CompanyTemplateView extends BaseReactElement<CompanyTemplateViewControl, CompanyTemplateViewState> {

    private columns = [{
        title: '企业模板名称',
        dataIndex: 'handle_name',
        key: 'handle_name',
        width: 500
    },
    {
        title: '行业类型',
        dataIndex: 'industry_type',
        key: 'industry_type',
        width: 150,
        render: (text: string, record: any, index: any) => {
            let industry = this.state.industry_data;
            if (text && industry) {
                return industry.get(text) ? industry.get(text) : text;
            }
        }
    },
    {
        title: '企业模板标识',
        dataIndex: 'handle_code',
        key: 'handle_code',
        width: 500,
        render: (text: string, record: any, index: any) => {
            return <a onClick={() => onRowSkipClick(this.props, record, index, ROUTE_PATH.companyTemplateDetail)}>{text}</a>;
        }
    },
    {
        title: '创建时间',
        width: 150,
        dataIndex: 'create_date',
        key: 'create_date'
    }];
    constructor(props: CompanyTemplateViewControl) {
        super(props);
        this.state = {
            page: 1,
            pageSize: 10,
        };
    }
    getdataService?() {
        return getObject(this.props.companyTemplateSignService_Fac!);
    }
    getIndustryService?() {
        return getObject(this.props.industryService_Fac!);
    }
    // 查询列表信息
    async queryList(condition: Condition, page: number, count: number) {
        const data = await this.getdataService!()!.get_company_list!(condition, page, count)!;
        // console.log('data--', data);
        const industry_data = await this.getIndustryService!()!.get_industry_list!()!;
        // console.log('industry_data--', industry_data);
        let industry_map = change_structure('industry_name', industry_data!.result);
        // console.log('data--11', industry_map);
        this.setState({
            total_data: data ? data!.total : 0, // 应当取接口返回的总数
            data_source: data ? data!.result : [],
            industry_data: industry_map
        });
    }

    private loadInfo = () => {
        this.setState({
            loading: true
        });
        let condition: Condition = {};
        this.queryList(condition, 1, 10)
            .then(() => {
                this.setState({
                    loading: false
                });
            })
            .catch(error => {
                this.setState({
                    loading: false
                });
                log("StatisticalAnalysisViewControl", error.message);
            });
    }
    // 查询回调
    private searchCategory = (e: any, val: any) => {
        this.setState({
            condition: val,
            loading: true
        });
        this.queryList(val, 1, this.state.pageSize ? this.state.pageSize : 10)
            .then(() => {
                this.setState({
                    loading: false
                });
            })
            .catch(error => {
                this.setState({
                    loading: false
                });
                log("StatisticalAnalysisViewControl", error.message);
            });
    }
    // 重置回调
    private reset = () => {
        console.log("重置回调");
        this.setState({
            condition: {}
        });
    }

    /** 分页回调事件 */
    pageOnCick = (contents: any) => {
        console.log('page:', contents);
        this.setState({
            page: contents,
            loading: true
        });
        this.queryList(this.state.condition ? this.state.condition! : {}, contents, this.state.pageSize!)
            .then(() => {
                this.setState({
                    loading: false
                });
            })
            .catch(error => {
                this.setState({
                    loading: false
                });
                log("StatisticalAnalysisViewControl", error.message);
            });
    }
    /** 改变分页数量回调事件 */
    showSizeChange = (current: number, pageSize: number) => {
        console.log('current: ' + current + 'pageSize: ' + pageSize);
        this.setState({
            pageSize: pageSize,
            loading: true
        });
        this.queryList(this.state.condition ? this.state.condition! : {}, 1, pageSize)
            .then(() => {
                this.setState({
                    loading: false
                });
            })
            .catch(error => {
                this.setState({
                    loading: false
                });
                log("StatisticalAnalysisViewControl", error.message);
            });
    }
    /** 自定义图标按钮回调事件 */
    onIconClick = (type: string, contents: any) => {
        if ('icon_edit' === type) {
            this.props.history!.push(ROUTE_PATH.changeCompanyTemplateView + `/${contents.id}`);
        }
    }
    componentDidMount() {
        this.loadInfo();
        // const currentCompanySign = IndustryInternetSignAppStorage.getCurrentCompanySign(),
        //     currentAccountPermission = IndustryInternetSignAppStorage.getCurrentUserRoles();
        // let currentAdminPermission = false, currentCompanyPermission = false;
        // for (const role of currentAccountPermission) {
        //     for (const permission of role.permission) {
        //         if (permission.permission === PermissionList.CompanyTemplate_Select_Admin.permission &&
        //             permission.permission_state === PermissionState.grant) {
        //             currentAdminPermission = true;
        //         }
        //         if (permission.permission === PermissionList.CompanyTemplate_Select_Company.permission &&
        //             permission.permission_state === PermissionState.grant) {
        //             currentCompanyPermission = true;
        //         }
        //     }
        // }
        // if (currentAdminPermission) {
        //     this.loadInfo();
        //     return;
        // }
        // if (currentCompanyPermission) {
        //     this.props.history!.push(`${this.props.current_company_sign_path}/${currentCompanySign.id}`);
        // }
    }
    componentWillMount() {
        const currentCompanySign = IndustryInternetSignAppStorage.getCurrentCompanySign();
        const currentAccountPermission = IndustryInternetSignAppStorage.getCurrentUserRoles();
        let currentCompanyPermission = false;
        for (const role of currentAccountPermission) {
            for (const permission of role.permission) {
                if (permission.permission === PermissionList.CompanyTemplate_Select_Admin.permission &&
                    permission.permission_state === PermissionState.grant) {
                    currentCompanyPermission = true;
                }

            }
        }
        if (!currentCompanySign && !currentCompanyPermission) {
            // 当为企业权限并且企业标识未创建，需提示并跳转至设置页面
            notification.open({
                message: '提示',
                description: '请联系管理员绑定企业',
                onClick: () => {
                    console.log('Notification Clicked!');
                },
            });
            this.props.history!.push(ROUTE_PATH.securitySettings);
        } else {
            // 当为企业权限并企业标识存在跳转值企业详情页面
            if (!currentCompanyPermission) {
                this.props.history!.push(`${ROUTE_PATH.companyTemplateDetail}/${currentCompanySign!.id!}`);
            }
        }
    }
    render() {
        let { data_source } = this.state;
        console.log(data_source);
        let sign_frame_props = {
            loading: this.state.loading,
            type_show: false,
            label_props: [
                {
                    text: "品类模板名称",
                    decorator_id: "handle_name",
                    option: {
                        placeholder: "请输入品类模板名称"
                    }
                },
                {
                    text: "品类模板标识",
                    decorator_id: "handle_code",
                    option: {
                        placeholder: "请输入品类模板标识"
                    }
                },
                {
                    text: "创建时间",
                    decorator_id: "create_date",
                }
            ],

            table_props: {
                columns: this.columns,
                dataSource: data_source,
            },
            pagination: {
                total: 500,
                pageSize: 10
            },
            edit_form_items_props: edit_form_items_props,
            showTable: (
                <NTOperationTable
                    bordered={false}
                    data_source={data_source}
                    on_icon_click={this.onIconClick}
                    columns_data_source={this.columns}
                    on_row_selection={undefined}
                    on_click_del={undefined}
                    table_size='middle'
                    showHeader={true}
                    total={this.state.total_data}
                    show_size_change={this.showSizeChange}
                    page_on_click={this.pageOnCick}
                    default_page_size={10}
                    total_pages={Math.ceil((this.state.total_data ? this.state.total_data : 0) / 10)}
                    show_footer={true}
                    other_label_type={[{ type: 'icon', label_key: 'icon_edit', label_parameter: { icon: 'antd@edit' } }]}
                    rowKey='id'
                />),
            search_cb: this.searchCategory,
            reset_cb: this.reset
        };
        return (
            <SignFrameLayout {...sign_frame_props} />
        );
    }
}

/**
 * 控件：企业模板标识视图控件控制器
 * 描述
 */
@addon('CompanyTemplateView', '企业模板标识视图控件', '企业模板标识视图控件控制器')
@reactControl(CompanyTemplateView, true)
export class CompanyTemplateViewControl extends BaseReactElementControl {
    /** 企业服务 */
    public companyTemplateSignService_Fac?: Ref<ICompanyTemplateSignService>;
    /** 行业类型服务 */
    public industryService_Fac?: Ref<IIndustryService>;
    /** 当前企业标识详情页Path */
    public current_company_sign_path?: string;
}